package com.anycl.customer.service.impl;

import com.anycl.customer.constant.Constants;
import com.anycl.customer.dao.AdminUserRepository;
import com.anycl.customer.dao.impl.AdminUserRepositoryImpl;
import com.anycl.customer.entity.AdminUser;
import com.anycl.customer.exception.CustomerException;
import com.anycl.customer.service.AdminUserService;
import com.anycl.customer.utils.BCryptPasswordEncoder;
import com.anycl.customer.utils.PasswordEncoder;
import com.anycl.customer.vo.UserVo;
import com.sun.xml.internal.bind.v2.runtime.reflect.opt.Const;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpSession;

@Slf4j
public class AdminUserServiceImpl implements AdminUserService {

    private AdminUserRepository userRepository = new AdminUserRepositoryImpl();

    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public UserVo signIn(AdminUser user) throws CustomerException {
        if (!user.validate())
            throw new CustomerException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        AdminUser oldUser = userRepository.getUserByUsername(user.getUsername());
        if (oldUser != null && oldUser.getId() != null)
            throw new CustomerException(Constants.ErrorMsg.EXIST_SAME_RECORD);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setStatus(Constants.OK_STATUS);
        int num = userRepository.signIn(user);
        if (num < 1)
            throw new CustomerException(Constants.ErrorMsg.UPDATE_ERROR);
        AdminUser adminUser = userRepository.getUserByUsername(user.getUsername());
        log.info("id " + adminUser.getId());
        return new UserVo(adminUser.getId(),adminUser.getUsername(), adminUser.getStatus());
    }

    @Override
    public UserVo login(AdminUser user, HttpSession httpSession) throws CustomerException {
        if (!user.validate())
            throw new CustomerException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        AdminUser oldUser = userRepository.getUserByUsername(user.getUsername());
        if (oldUser == null)
            throw new CustomerException(Constants.ErrorMsg.CAN_NOT_FOUND_RECORD);
        if (oldUser.getStatus().equals(Constants.NOT_OK_STATUS))
            throw new CustomerException(Constants.ErrorMsg.STATUS_ERROR);
        if (!passwordEncoder.matches(user.getPassword(), oldUser.getPassword()))
            throw new CustomerException(Constants.ErrorMsg.PASSWORD_ERROR);
        UserVo userVo = new UserVo(oldUser.getId(), oldUser.getUsername(), oldUser.getStatus());
        httpSession.setAttribute(Constants.CURRENT_USER, userVo);
        return userVo;
    }

    public UserVo checkLogin(HttpSession session) {
        return (UserVo) session.getAttribute(Constants.CURRENT_USER);
    }
}
